<template>
  <PageContainer>
    <view class="container">
      <Header title="发布供需" :data="{ isInit }" :is-custom-back="true" @go-back="handleGoBack">
        <template>
          <view>
            <template v-if="releaseType === ReleaseTypeEnum.insteadMember">
              <CustomTopTips :text="`发布成功后，代发会员将不可修改，请谨慎选择;`"></CustomTopTips>
            </template>
          </view>
        </template>
      </Header>
      <view class="p-12">
        <UniForms :modelValue="businessOpportunitiesFormData" ref="businessOpportunitiesFormRef">
          <view class="p-12 bgf br-8">
            <view id="error-memberId"></view>
            <UniFormsItem
              v-if="releaseType === ReleaseTypeEnum.insteadMember"
              label="发布会员"
              :required="true"
              :labelWidth="70"
              name="memberId"
              :contentRight="true"
              :rules="[{ required: true, errorMessage: '请选择发布会员' }]"
            >
              <PublishedMember v-model:modelValue="businessOpportunitiesFormData.memberId" />
            </UniFormsItem>
            <UniFormsItem label="供需类型" :labelWidth="70" label-position="top" :required="true">
              <BusiOppTypes
                :modelValue="businessOpportunitiesFormData.boType"
                @update:model-value="handleUpdBoType"
              ></BusiOppTypes>
            </UniFormsItem>
          </view>
          <view class="p-12 bgf br-8 mt-12" style="padding-top: 0 !important">
            <view id="error-title"></view>
            <!-- :label="`${
                businessOpportunitiesFormData.boType === BoTypeEnum.Supply ? '供应' : '需求'
              }标题`" -->
            <UniFormsItem
              label-position="top"
              :rules="[
                {
                  required: true,
                  errorMessage: `请填写标题`,
                },
              ]"
              :labelWidth="70"
              name="title"
            >
              <FormInput
                v-model:modelValue="businessOpportunitiesFormData.title"
                :placeholder="`请输入${
                  businessOpportunitiesFormData.boType === BoTypeEnum.Supply ? '供应' : '需求'
                }的标题（必填）`"
                :inputBorder="false"
              ></FormInput>
            </UniFormsItem>

            <view class="disFlx flexEnd" style="border-top: 1px solid #ebedf0">
              <TImage
                height="80rpx"
                src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/qiehuan.png"
                mode="heightFix"
                @click="handleChangeShowDetail"
              ></TImage>
            </view>
            <view id="error-details"></view>
            <UniFormsItem
              v-if="showDetail"
              name="details"
              label-position="top"
              :rules="[
                {
                  required: true,
                  errorMessage: `请填写详情`,
                },
              ]"
            >
              <PageComponents
                ref="pageComponentsRef"
                @loading-complete="setComponentsDetails"
              ></PageComponents>
            </UniFormsItem>

            <UniFormsItem
              v-else
              :label="`${
                businessOpportunitiesFormData.boType === BoTypeEnum.Supply ? '供应详情' : '需求详情'
              }`"
              :required="true"
              :labelWidth="100"
              name="details"
              :contentRight="true"
              :rules="[
                {
                  required: true,
                  errorMessage: `请填写详情`,
                },
              ]"
            >
              <EditDetail
                :model-value="businessOpportunitiesFormData.details"
                @update:model-value="handleEditDetailUpdate"
                :boType="businessOpportunitiesFormData.boType"
              />
            </UniFormsItem>
          </view>

          <view class="p-12 bgf br-8 mt-12">
            <view id="error-cooperationTypeId"></view>
            <UniFormsItem
              label="合作类型"
              :required="true"
              name="cooperationTypeId"
              :labelWidth="100"
              :contentRight="true"
              :rules="[
                {
                  required: true,
                  errorMessage: `请选择合作类型`,
                },
              ]"
            >
              <FormSelector
                v-model:model-value="businessOpportunitiesFormData.cooperationTypeId"
                :localdata="cooperationTypeList"
                :border="false"
              />
            </UniFormsItem>
            <view id="error-industryCategoryIdList"></view>
            <UniFormsItem
              :label="
                businessOpportunitiesFormData.boType === BoTypeEnum.Demand ? `行业要求` : '所属行业'
              "
              :required="true"
              label-position="top"
              name="industryCategoryIdList"
              :rules="[
                {
                  required: true,
                  errorMessage: `请选择行业`,
                },
              ]"
            >
              <FormSelectIndustry
                v-model:model-value="businessOpportunitiesFormData.industryCategoryIdList"
              />
            </UniFormsItem>

            <UniFormsItem
              :label="`${
                businessOpportunitiesFormData.boType === BoTypeEnum.Supply ? '供应' : '需求'
              }内容附件`"
              label-position="top"
              name="attachmentUrls"
            >
              <FormUploadFile
                v-model:model-value="businessOpportunitiesFormData.attachmentUrls"
                mediaType="doc"
                width="208rpx"
                height="208rpx"
                :limit="5"
              />
              <view class="fz-14" style="color: #999996; word-break: break-all">
                请上传大小不超过 50MB，格式为 doc/docx/xls/xlsx/ppt/pdf 的文件，最多5个
              </view>
            </UniFormsItem>
            <UniFormsItem :label="`合作地区`" :labelWidth="100" :contentRight="true">
              <BoAddress v-model:address-codes="addressCodes" />
            </UniFormsItem>

            <UniFormsItem label="可合作期限" :labelWidth="100" :contentRight="true">
              <CoopPeriod
                v-model:cooperation-datetime="businessOpportunitiesFormData.cooperationDatetime"
                v-model:cooperation-duration-type="
                  businessOpportunitiesFormData.cooperationDurationType
                "
              />
            </UniFormsItem>
            <UniFormsItem
              :required="true"
              label="提交意向需填写信息"
              :labelWidth="200"
              :contentRight="true"
            >
              <view class="disFlxJS pr-10" style="color: #999996" @click="handleSetForm">
                <text>
                  {{ formItemList.length ? `已设置${formItemList.length}项` : '请设置收集表单' }}
                </text>
                <text class="ant-iconfont fz-12 ml-5">&#xe77e;</text>
              </view>
            </UniFormsItem>
          </view>
          <view class="p-12 bgf mt-12 br-8">
            <UniFormsItem label="撮合激励" :contentRight="true" name="incentiveOpen">
              <FormSwitch v-model:modelValue="incentiveOpen"></FormSwitch>
            </UniFormsItem>

            <template v-if="incentiveOpen">
              <view class="fz-14 linh-20 mb-22" style="color: #999996">
                注：仅供秘书处成员可见，无需线上支付，具体激励情况以及结算方式由线下再自由处理。
              </view>

              <UniFormsItem label="" name="incentiveType" labelPosition="top">
                <FormDataCheckbox
                  v-model.number="businessOpportunitiesFormData.incentiveType"
                  :localdata="[
                    {
                      value: IncentiveTypeEnum.Commission,
                      text: '佣金激励',
                    },
                    {
                      value: IncentiveTypeEnum.Other,
                      text: '其它激励',
                    },
                  ]"
                ></FormDataCheckbox>
              </UniFormsItem>
              <view id="error-estimatedScale"></view>
              <UniFormsItem
                v-if="incentiveType === IncentiveTypeEnum.Commission"
                label="预估规模"
                labelWidth="100"
                :contentRight="true"
                :required="true"
                name="estimatedScale"
                :rules="[
                  {
                    required: true,
                    errorMessage: '请选择预估规模',
                  },
                ]"
              >
                <view
                  class="disFlxAC br-4 pr-16 pl-6 py-4"
                  style="background-color: #f2f3f5; width: 240rpx"
                >
                  <FormInput
                    v-model:model-value="businessOpportunitiesFormData.estimatedScale"
                    :input-border="false"
                  />
                  <text>元</text>
                </view>
              </UniFormsItem>
              <view id="error-incentiveCommissionRate"></view>
              <UniFormsItem
                v-if="incentiveType == IncentiveTypeEnum.Commission"
                label="成交佣金比例"
                name="incentiveCommissionRate"
                :contentRight="true"
                labelWidth="100"
                :required="true"
                :rules="[
                  {
                    required: true,
                    errorMessage: '请填写佣金比例',
                  },
                ]"
              >
                <view
                  class="disFlxAC br-4 pr-16 pl-6 py-4"
                  style="background-color: #f2f3f5; width: 240rpx"
                >
                  <FormInput
                    v-model:model-value="businessOpportunitiesFormData.incentiveCommissionRate"
                    :input-border="false"
                  />
                  <text>%</text>
                </view>
              </UniFormsItem>
              <view id="error-incentiveDetails"></view>
              <UniFormsItem
                v-if="incentiveType == IncentiveTypeEnum.Other"
                label="激励说明"
                name="incentiveDetails"
                labelPosition="top"
                :required="true"
                :rules="[
                  {
                    required: true,
                    errorMessage: '请填写激励说明',
                  },
                ]"
              >
                <FormInput
                  v-model:model-value="businessOpportunitiesFormData.incentiveDetails"
                  :input-border="false"
                  :maxlength="60"
                  type="textarea"
                  placeholder="例如：赠送本店一次xx项目免费体验等"
                  :autoHeight="true"
                  :styles="{
                    backgroundColor: '#F2F3F5',
                    height: '160rpx',
                  }"
                />
              </UniFormsItem>
            </template>
          </view>
        </UniForms>
      </view>

      <TButtonGroup v-if="isInit" :styles="{ backgroundColor: '#fff' }">
        <TButton
          v-if="
            businessOpportunitiesFormData.boStatus === BoStatusEnum.Draft ||
            !businessOpportunitiesFormData.id
          "
          class="gutter-btn"
          text="保存并预览"
          type="none"
          custom-class="borderBtn"
          @click.stop="handleSave"
        />

        <TButton class="gutter-btn" text="发布供需" type="primary" @click.stop="handleSubmit" />
      </TButtonGroup>
      <PerfectInfoDialog />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* releaseBusinessOpportunities 发布供需 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import UniForms from '@/components/Form/uni_modules/uni-forms/uni-forms.vue';
  import UniFormsItem from '@/components/Form/uni_modules/uni-forms-item/uni-forms-item.vue';
  import BusiOppTypes from './components/BusiOppTypes.vue';
  import FormInput from '@/components/Form/components/FormInput.vue';
  import FormSelectIndustry from './components/FormSelectIndustry.vue';
  import FormSelector from '@/components/Form/components/FormSelector.vue';
  import FormUploadFile from '@/components/Form/components/upload/FormUploadFile.vue';
  import CoopPeriod from './components/CoopPeriod.vue';
  import PublishedMember from './components/PublishedMember.vue';
  import FormDataCheckbox from '@/components/Form/components/FormDataCheckbox.vue';
  import FormSwitch from '@/components/Form/components/FormSwitch.vue';
  import EditDetail from './components/EditDetail.vue';
  import { computed, getCurrentInstance, provide, ref } from 'vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { navigateTo, onLoad, redirectTo } from '@/router';
  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';
  import {
    BoStatusEnum,
    BoTypeEnum,
    CooperationDurationTypeEnum,
    IncentiveOpenEnum,
    IncentiveTypeEnum,
    ReleaseTypeEnum,
  } from '@/enums/businessOpportunitiesEnum';
  import type { IBusinessOpportunity } from '@/api/businessOpportunities/type';
  import {
    createBusinessOpportunities,
    editBusinessOpportunities,
    getBusinessOpportunities,
    getCooperationTypeList,
    publishBo,
  } from '@/api/businessOpportunities';
  import { Toast } from '@/utils';
  import type { ComponentType, Localdata } from '@/components/Form/types';
  import CustomTopTips from '@/components/CustomTopTips/index.vue';
  import BoAddress from './components/BoAddress.vue';
  import { useBackBeforeUnload, type UseNavigateBackOptions } from '@/hooks/core/useNavigateBack';
  import PageComponents from '../editBusinessOpportunitiesDetail/components/PageComponents.vue';
  import TImage from '@/components/TImage/index.vue';
  import type { AddFormItemData } from '@/api/membership/formCompTypes';
  import type { ComponentProps, FormSchema } from '@/components/Form';
  import { IsRequired } from '@/enums/formEnum';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { useSupplyDemandStore } from '@/store/modules/supplyDemand';
  import { isArray, isString } from 'lodash-es';
  import { isNumber } from '@/utils/is';
  import type { ReleaseBusinessOpportunities } from '@/router/types/modules';
  import { useUserStore } from '@/store/modules/user';
  const { setFormItemListCache, clearFormItemListCache } = useSupplyDemandStore();

  const releaseType = ref<ReleaseTypeEnum>();
  provide('releaseType', releaseType);
  const businessOpportunitiesFormData = ref<IBusinessOpportunity>({
    id: void 0,
    boType: BoTypeEnum.Supply,
    title: '',
    cooperationTypeId: void 0,
    cooperationTypeName: '',
    industryCategoryIdList: [],
    details: '',
    provinceId: void 0,
    cityId: void 0,
    provinceName: '',
    cityName: '',
    cooperationDurationType: CooperationDurationTypeEnum.LongTerm,
    cooperationDatetime: '',
    incentiveOpen: IncentiveOpenEnum.No,
    incentiveType: IncentiveTypeEnum.Commission,
    incentiveDetails: '',
    incentiveCommissionRate: void 0,
    estimatedScale: '',
    attachmentUrls: [],
    shareKey: '',
    boFormDto: {
      customFormItemList: [],
    },
  });

  const pageComponentsRef = ref<InstanceType<typeof PageComponents>>();
  const copyForm = ref('');
  let success: ReleaseBusinessOpportunities['success'];

  onLoad<'releaseBusinessOpportunities'>(async (op) => {
    success = op.success;
    isInit.value = true;
    businessOpportunitiesFormData.value.id = op.id;
    businessOpportunitiesFormData.value.shareKey = op.shareKey;
    releaseType.value = op.releaseType;
    queryCooperationTypeList();
    if (op.id) {
      await getFormData();
    }
    copyForm.value = JSON.stringify(businessOpportunitiesFormData.value);
  });

  const showDetail = ref(true);

  // 设置供需详情回显
  const setComponentsDetails = (details?: string) => {
    pageComponentsRef.value?.setData({
      editBusinessOpportunitiesDetail: details || businessOpportunitiesFormData.value.details,
      boType: businessOpportunitiesFormData.value.boType,
    });
  };

  // 设置表单供需详情值
  const setFormDetails = () => {
    businessOpportunitiesFormData.value.details = pageComponentsRef.value?.getData() || '';
  };

  const handleEditDetailUpdate = (value: string) => {
    setComponentsDetails(value);
    setFormDetails();
  };
  const isInit = ref(false);

  const handleChangeShowDetail = () => {
    setFormDetails();
    showDetail.value = !showDetail.value;
  };

  // 编辑回显
  const getFormData = async () => {
    const res = await getBusinessOpportunities(
      businessOpportunitiesFormData.value.id!,
      releaseType.value,
    );
    /** 回填表单列表 */
    const list: FormSchema[] = [];
    res.boFormVo?.formItemList.forEach((item) => {
      list.push({
        field: item.id.toString(),
        label: item.showName,
        component: item.itemType,
        defaultValue: item.itemDefault,
        required: item.isRequired === IsRequired.REQUIRED,
        dataType: item.fieldLibraryId?.toString(),
        dynamicDisabled: item.disabled,
        componentProps: {
          placeholder: item.value,
          localdata: localDataMapping(item.customFormItemAnswerList, {
            label: 'words',
            value: 'id',
          }),
        },
      });
    });

    delete res.boFormVo;
    businessOpportunitiesFormData.value = res;

    formItemList.value = list;

    setComponentsDetails();
  };

  const cooperationTypeList = ref<Localdata[]>([]);
  const queryCooperationTypeList = async () => {
    const res = await getCooperationTypeList();
    cooperationTypeList.value = res.map((item) => ({
      text: item.cooperationTypeName,
      value: item.id,
    }));
  };

  const incentiveOpen = computed({
    get() {
      return !!businessOpportunitiesFormData.value.incentiveOpen;
    },
    set(val) {
      businessOpportunitiesFormData.value.incentiveOpen = val ? 1 : 0;
    },
  });

  const incentiveType = computed(() => {
    return businessOpportunitiesFormData.value.incentiveType;
  });

  const addressCodes = computed({
    get() {
      const { provinceId, cityId } = businessOpportunitiesFormData.value;
      if (provinceId && cityId) return [provinceId, cityId];
      return [];
    },
    set(arr: number[]) {
      businessOpportunitiesFormData.value.provinceId = arr[0];
      businessOpportunitiesFormData.value.cityId = arr[1];
    },
  });

  const businessOpportunitiesFormRef = ref<InstanceType<typeof UniForms>>();

  const formItemList = ref<FormSchema[]>([]);

  /** 设置表单 */
  function handleSetForm() {
    setFormItemListCache(formItemList.value);
    navigateTo({
      name: 'businessOpportunitiesFormCreate',
      options: {
        id: businessOpportunitiesFormData.value.id!,
        success: (list) => {
          formItemList.value = list;
          clearFormItemListCache();
        },
      },
    });
  }

  /**
   * 保存草稿
   */
  const handleSubmitDraft = async () => {
    await submitBusinessOpportunities();
    Toast('保存成功');
  };

  const handleSave = async () => {
    await handleSubmitDraft();
    redirectTo({
      name: 'supplyDemandDetails',
      options: {
        id: businessOpportunitiesFormData.value.id!,
        shareKey: undefined,
      },
    });
  };
  const ins: any = getCurrentInstance();
  const submitBusinessOpportunities = () => {
    return new Promise(async (resolve, reject) => {
      setFormDetails();
      await businessOpportunitiesFormRef.value
        ?.validate()
        .then(async () => {
          if (!businessOpportunitiesFormData.value.details) {
            Toast(
              `请填写${
                businessOpportunitiesFormData.value.boType === BoTypeEnum.Supply ? '供应' : '需求'
              }详情`,
            );
            return reject('请填写详情');
          }
          if (!formItemList.value.length) {
            Toast('请设置收集表单');
            return reject('请设置收集表单');
          }
          const res = await requestApi();
          return resolve(res);
        })
        .catch((r: { key: string }[]) => {
          if (r[0]) {
            uni
              .createSelectorQuery()
              .in(ins.proxy)
              .select(`#error-${r[0].key}`)
              .boundingClientRect()
              .exec((res) => {
                uni.pageScrollTo({
                  scrollTop: res[0].top - uni.upx2px(476),
                  duration: 300,
                });
              });
          }

          reject();
        });
    });
  };

  /** 数据提交 */
  async function requestApi() {
    const data: AddFormItemData[] = [];

    formItemList.value.forEach((v) => {
      const id = isNumber(v.field) ? Number(v.field) : null;
      const label = v.label as string;
      const componentProps = v.componentProps as ComponentProps;
      const localdata =
        componentProps && isArray(componentProps?.localdata)
          ? (componentProps?.localdata as Localdata[])
          : [];
      data.push({
        id: id,
        name: label,
        showName: label,
        itemType: v.component as ComponentType,
        isRequired: v.required ? IsRequired.REQUIRED : IsRequired.NOTREQUIRED,
        value: componentProps?.placeholder as string,
        fieldLibraryId: v.dataType,
        customFormItemAnswerDtoList: localdata.map((v) => {
          return {
            id: isString(v.value) ? null : v.value,
            words: v.text,
          };
        }),
      });
    });

    businessOpportunitiesFormData.value.boFormDto = {
      customFormItemList: data,
    };
    if (businessOpportunitiesFormData.value.id) {
      const res = await editBusinessOpportunities(
        businessOpportunitiesFormData.value,
        releaseType.value,
      );

      businessOpportunitiesFormData.value = res;
    } else {
      const res = await createBusinessOpportunities(
        businessOpportunitiesFormData.value,
        releaseType.value,
      );
      businessOpportunitiesFormData.value = res;
    }
    success?.();
    return businessOpportunitiesFormData.value;
  }
  const useUser = useUserStore();
  /** 发布供需 */
  async function handleSubmit() {
    await useUser.validatePerfectionInfo();
    await submitBusinessOpportunities();
    const id = businessOpportunitiesFormData.value.id;
    const res = await publishBo(id!, releaseType.value!);
    success?.();
    if (releaseType.value === ReleaseTypeEnum.member && res.boStatus !== BoStatusEnum.Active) {
      redirectTo({
        name: 'releaseBoResult',
        options: {
          id: res.id!,
          reviewRecordId: res.reviewRecordId!,
        },
      });
    } else {
      Toast({
        title: '发布成功',
        icon: 'success',
        success: () => {
          UniNavigateBack();
        },
      });
    }
    // redirectTo({
    //   name: 'businessOpportunitiesFormCreate',
    //   options: {
    //     id: businessOpportunitiesFormData.value.id!,
    //     releaseType: releaseType.value!,
    //   },
    // });
  }

  const backOptions = ref<UseNavigateBackOptions>({
    enableBeforeUnload: true,
    backMessage: '此操作会放弃已编辑的内容，是否确认退出？',
    showModalOptions: {
      title: '退出编辑提示',
      content:
        '是否要将已填写的内容保存？保存后将存为一个供需草稿，下次可通过供需列表选择相应草稿进入继续编辑。',
      showCancel: true,
      cancelColor: '#969799',
      confirmColor: '#2878FF',
      confirmText: '保存',
      cancelText: '不保存',
    },
    confirmCallback: async (result) => {
      await handleSubmitDraft();
    },
  });

  const { interceptNavigateBack, UniNavigateBack } = useBackBeforeUnload(backOptions);

  const handleGoBack = () => {
    setFormDetails();
    if (copyForm.value === JSON.stringify(businessOpportunitiesFormData.value)) {
      UniNavigateBack();
    } else {
      interceptNavigateBack();
    }
  };

  const handleUpdBoType = (boType: BoTypeEnum) => {
    businessOpportunitiesFormData.value.boType = boType;
    pageComponentsRef.value?.updateBoType(boType);
  };
</script>

<style lang="scss" scoped>
  .action-area {
    display: flex;
    width: 100vw;
    box-sizing: border-box;
    &__item {
      box-sizing: border-box;
      flex-shrink: 0;
      width: 100vw;
      height: 100%;
      position: relative;
    }
  }
</style>
